package org.wltea.dichotload;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.cfg.DefaultConfig;
import org.wltea.analyzer.dic.Dictionary;

public class DicLoadTask extends TimerTask {
    private static final Logger logger = LoggerFactory.getLogger(DicLoadTask.class);
    
    private static final String hotLoadFilePath = "/hotLoadDict";
   
    private ServletContext servletContext;

    DicLoadTask(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void run() {
        try {
            DefaultConfig.getInstance().reloadConfig();

            extractHotDicFromDB();

            logger.info("----HotDic ReLoad Start----");

            Dictionary.initial(DefaultConfig.getInstance()).loadHotLoadDict();

            Dictionary.initial(DefaultConfig.getInstance()).loadExtDict();

            logger.info("----HotDic ReLoad End----");
        } catch (Exception e) {
            logger.error("HotDic ReLoad  has error:",e);
        }
    }

    private void extractHotDicFromDB() {
        try {
            Class.forName(DefaultConfig.getInstance().getjdbcDriver());
            Connection con = DriverManager.getConnection(DefaultConfig.getInstance().getjdbcUrl(),
                    DefaultConfig.getInstance().getjdbcUser(), DefaultConfig.getInstance().getjdbcPassword());
            Statement stmt = con.createStatement();

            String[] sqlArray = DefaultConfig.getInstance().getDictSqlList();
            for (String dicSql : sqlArray) {
                String dicSqlLowerCase = dicSql.toLowerCase();

                String fileName = dicSql.substring(dicSqlLowerCase.indexOf("as ") + 3, dicSqlLowerCase.indexOf("from "))
                        .replaceAll(" ", "") + ".dic";

                String pathDir = getClass().getResource("/").getPath() + hotLoadFilePath + "/";
                File pathDirFile = new File(pathDir);
                if (!pathDirFile.exists()){
                    pathDirFile.mkdirs();
                    logger.info(String.format("Writer dictFile:%s",pathDir));
                }
                
                File dictFile = new File(pathDir+fileName);
                if (!dictFile.exists()){
                    dictFile.createNewFile();
                    logger.info(String.format("Writer dictFile:%s",pathDir+fileName));
                }
                

                ResultSet result = stmt.executeQuery(dicSql);

                FileOutputStream dictFileOutputStream = new FileOutputStream(dictFile);
                BufferedWriter dictFileWriter = new BufferedWriter(
                        new OutputStreamWriter(dictFileOutputStream, "utf-8"));

                Map<String,String> distinctMap = new HashMap<String,String>();
                while (result.next()) {
                    dataEtl(distinctMap, result.getString(1));
                }

                Iterator sfds = distinctMap.entrySet().iterator();
                while (sfds.hasNext()) {
                    Map.Entry entry = (Map.Entry) sfds.next();
                    Object key = entry.getKey();
                    dictFileWriter.write(key + "\n");
                    dictFileWriter.flush();
                }

                dictFileOutputStream.close();
            }
        } catch (Exception e) {
            logger.error("extractHotDicFromDB has error:", e);
        }
    }

    public void writeWorldNotRepeat(BufferedReader dictFileReader, BufferedWriter dictFileWriter, String world)
            throws IOException {
        String tempString = null;
        while ((tempString = dictFileReader.readLine()) != null) {
            if (world.equals(tempString))
                return;
        }

        dictFileWriter.write(world + "\n");
        dictFileWriter.flush();
    }

    private void dataEtl(Map<String,String> distinctMap, String oldWrod) {
        String newWord = oldWrod.replaceAll(" ", "").replaceAll("\t", "0");

        newWord = newWord.replaceAll("\"", "").replaceAll("(\\d+)号", "").replaceAll("(\\d+)弄", "").replaceAll("(\\d+)室",
                "");

        String[] wordArray = newWord.split("[·]|[.]|[、]|[,]|[，]|[】]|[【]|[）]|[（]|[(]|[)]|[•]");
        for (String word : wordArray) {
            if ((word != null) && (!"".equals(word)) && (word.length() != 1) && (!word.matches("[0-9]+")))
                distinctMap.put(word, "1");
        }
    }
}